<?php
/**
 * Created by PhpStorm.
 * User: jsq
 * Date: 2017/12/5 0005
 * Time: 10:33
 */

namespace app\common\logic;

use app\admin\controller\common;
use app\admin\model\Users;


class Login
{

    /**
     * 执行登录
     * @param $username
     * @param $password
     * @return array
     */
    public function executLogin($username,$password){
        $username = trim($username);
        $password = trim($password);
        if(is_numeric($username)){
            $map['phone'] = $username;
        } else {
            $map['username'] = $username;
        }
        $user_model  = new Users();
        $user = $user_model::get($map);
        if (empty($user)){
            return ['result'=>2,'msg'=>'用户不存在'];
        } elseif ($user['status'] != 1){
            return ['result'=>2,'msg'=>'用户被禁用'];
        } else {
            if (md5($password)!==$user['password']) {
                return ['result'=>2,'msg'=>'用户名或者密码错误'];
            }else{
                $id = $user['id'];
                // 更新登录信息
                $user['counts'] = $user['counts']+1;
                if ($user->save()) {
                    // 自动登录
                    $this->auto_login(db('users')->where(['id'=>$id])->find());
                }
                return ['result'=>1,'msg'=>'登录成功'];
            }
        }
    }


    /**
     * 自动登录
     * @param mixed $user 用户对象
     * @param bool $rememberme 是否记住登录，默认7天
     */
    public static function auto_login($user, $rememberme = false)
    {
        // 记录登录
        $auth = array(
            'adminid'    => $user['id'],
            'username'   => $user['username'],
            'depar_id'   => $user['depar_id'],
            'position'   => $user['position'],
            'avatar'     => $user['avatar'],
        );
        $msg = '登陆成功';
        logdaily(1,$auth['username'],$msg);
        session('admin_user', $auth);
        // 记住登录
        if ($rememberme) {
            $signin_token = $user->username.$user->id;
            cookie('aid', $user->id, 24 * 3600 * 7);
            cookie('signin_token', ($signin_token), 24 * 3600 * 7);
        }
    }



}